var express = require('express');
var router = express.Router();

/**
 * 响应get
 * curl http://localhost:3000/api\?name\=1111 -X GET
 */
router.get('/', function (req, res, next) {
    var result = {method: 'GET', query: req.query};

    if (req.query.errFlag === 'true') {
        res.status(400);
    }

    res.contentType("json");
    res.send(result);
});

/**
 * 响应post
 *
 * curl http://localhost:3000/api -X POST -i -H "Content-Type:application/x-www-form-urlencoded;charset=utf-8" -d "param1=value1" -d "param2=value2"
 */
router.post('/', function (req, res, next) {
    var result = {method: 'POST', body: req.body};

    if (req.body.errFlag === 'true') {
        res.status(400);
    }

    res.contentType("json");
    res.send(result);
});

/**
 * 响应put
 */
router.put('/', function (req, res, next) {
    var result = {method: 'PUT', body: req.body};

    if (req.body.errFlag === 'true') {
        res.status(400);
    }

    res.contentType("json");
    res.send(result);
});

/**
 * 响应delete
 */
router.delete('/', function (req, res, next) {
    var result = {method: 'DELETE', body: req.body};

    if (req.body.errFlag === 'true') {
        res.status(400);
    }

    res.contentType("json");
    res.send(result);
});

module.exports = router;

// 命令行测试
// curl http://localhost:3000/api -X PUT -i -H "Content-Type:application/json" -d '{"errFlag" : false, "foo" : "bar"}'

// curl http://localhost:3000/api -X POST -i -H "Content-Type:application/x-www-form-urlencoded;charset=utf-8" -H "Accept-Encoding:gzip" -d "param1=value1" -d "param2=value2"
